package com.bootdo.wx.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.builder.TextMessageBuilder;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.config.WxMaConfiguration;
import com.bootdo.common.config.WxMaProperties;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.wx.dao.GoodsGoodsDao;
import com.bootdo.wx.dao.GoodsProductDao;
import com.bootdo.wx.dao.OrderDetailDao;
import com.bootdo.wx.dao.OrderShippingDao;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.enums.OrderStatus;
import com.bootdo.wx.service.MemberUserService;
import com.bootdo.wx.service.OrderBackService;
import com.bootdo.wx.service.OrderOrderService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/api/wxController")
public class ApiWxController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMaProperties properties;

    @Autowired
    private OrderOrderService orderOrderService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private GoodsGoodsDao goodsGoodsDao;
    @Autowired
    private GoodsProductDao goodsProductDao;
    @Autowired
    private OrderBackService orderBackService;
    @Autowired
    private OrderShippingDao orderShippingDao;



   /* @GetMapping({"/checkSignature"})
    public void checkSignature(@RequestParam("msg_signature") String msg_signature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) {
        System.out.println("---------------------------::" + msg_signature + "---" + timestamp + "------" + nonce + "-------------" + echostr);
        boolean b = WxCpConfiguration.getCpService(((AppConfig)this.wxCpProperties.getAppConfigs().get(0)).getAgentId()).checkSignature(msg_signature, timestamp, nonce, echostr);
        System.out.println(b);
    }*/

    /**
     * 验证微信消息
     * @param request
     * @param response
     */
    @GetMapping("/checkSignature")
    public void checkSignature(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("request"+request);
            // 微信加密签名
            String signature = request.getParameter("signature");
            System.out.println("signature:"+signature);

            // 时间戳
            String timestamp = request.getParameter("timestamp");

            // 随机数
            String nonce = request.getParameter("nonce");

            // 随机字符串
            String echostr = request.getParameter("echostr");

            final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
            boolean b = wxService.checkSignature(timestamp, nonce, signature);
            if(b){
                response.getOutputStream().write(echostr.getBytes());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /***
     * 接收微信消息
     * @param request
     * @param response
     */
    @PostMapping("/checkSignature")
    public void  receiveMsg(HttpServletRequest request, HttpServletResponse response) {
        String body = ServletUtil.getBody(request);
        if (StringUtils.isNotBlank(body)) {
            // 消息回复
            editMessage(body,response);
        } else {
            log.info("客服信息解密失败,不作处理");
        }
    }



    public void editMessage(String msg,HttpServletResponse response) {
        try{
            JSONObject strj = (JSONObject) JSONObject.parseObject(msg);
            System.out.println("strj"+strj);
            // 用户openID
            String openID = strj.getString("FromUserName");
            // 消息类型
            String msgType = strj.getString("MsgType");
            log.info("日志:---用户:[{}]在:[{}]时间发送类型[{}]消息:[{}]", openID, strj.getString("CreateTime"), msgType,
                    strj.getString("Content"));
            if ("event".equals(msgType)) {
                // 用户点击进入客服时不发送消息
                /*SortedMap<String ,String > sortedMap = new TreeMap();
                sortedMap.put("ToUserName",openID);
                sortedMap.put("FromUserName","wxid_24igbtwt8l3822");
                sortedMap.put("CreateTime",strj.getString("CreateTime"));
                sortedMap.put("MsgType","transfer_customer_service");
                System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                System.out.println("parseXML(sortedMap):"+parseXML(sortedMap));
                response.getWriter().write(parseXML(sortedMap));*/
                //包含SessionFrom 返订单得售后格式
                if(strj.containsKey("SessionFrom")&&null!=strj.getString("SessionFrom")&&!"".equals(strj.getString("SessionFrom"))&&strj.getString("SessionFrom").length()>10){
                    String sessionFrom = strj.getString("SessionFrom");
                    OrderOrderDO orderOrderDO = orderOrderService.get(sessionFrom);
                    sendMessage(openID,orderOrderDO);
                }else{
                    //直接转到客服
                    SortedMap<String ,String > sortedMap = new TreeMap();
                    sortedMap.put("ToUserName",openID);
                    sortedMap.put("FromUserName",strj.getString("ToUserName"));
                    sortedMap.put("CreateTime",strj.getString("CreateTime"));
                    sortedMap.put("MsgType","transfer_customer_service");
                    cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(sortedMap);
                    String s = jsonObject.toJSONString(4);
                    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+s);
                  /*  System.out.println("parseXML(sortedMap):"+parseXML(sortedMap));*/
                    response.getWriter().write(s);
                }



            }else{

                    //返回xml 给微信,转发到网页版客服  小程序后台配置得是json就返回json  配置得xml就返回xml
                    //strj.getString("ToUserName")
                    SortedMap<String ,String > sortedMap = new TreeMap();
                    sortedMap.put("ToUserName",openID);
                    sortedMap.put("FromUserName",strj.getString("ToUserName"));
                    sortedMap.put("CreateTime",strj.getString("CreateTime"));
                    sortedMap.put("MsgType","transfer_customer_service");
                    cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(sortedMap);
                    String s = jsonObject.toJSONString(4);
                    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+s);
                    //System.out.println("parseXML(sortedMap):"+parseXML(sortedMap));
                    response.getWriter().write(s);




            }
           /* Map<String, String> contentMap = new HashMap<String, String>();
            contentMap.put("title", "标题");
            contentMap.put("description", "描述");
            contentMap.put("url", "连接");
            contentMap.put("thumb_url", "展示图地址");*/

            // getToken()方法为获取token信息，因为会存在token不存在的情况，所以封装了一下
            //String token = memberTokenService.getToken();

            //sendMessage(openID, "link", contentMap, token);
           /* MemberUserDO memberUserDO = memberUserService.queryByOpenid(openID);
            Map<String,Object> map = new HashMap<>();
            map.put("latitude",memberUserDO.getLatitude());
            map.put("longitude",memberUserDO.getLongitude());
            MemberUserDgDO latelyService = memberUserDgService.getLatelyService(map);*/


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendMessage(String openID,OrderOrderDO orderOrderDO) throws WxErrorException {
        final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
        //System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%latelyService.getQrCode()"+latelyService.getQrCode());
        //File file = ImageUtils.getFile(latelyService.getQrCode());*/

        //WxMediaUploadResult image = wxService.getMediaService().uploadMedia("image", file);
        MemberUserDO memberUserDO = memberUserService.get(orderOrderDO.getUserId());
        List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(orderOrderDO.getId());
        GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(MapUtil.getStr(byOrderId.get(0), "goodId"));
        Integer total = MapUtil.getInt(byOrderId.get(0), "total");
        OrderBackDO orderBackDO = orderBackService.getByOrderId(orderOrderDO.getId());

        String backExpressCode = "无";
        if(orderBackDO!=null){
            backExpressCode = orderBackDO.getExpressCode();
        }

        String backReason = "无";
        if(orderBackDO!=null&&StringUtils.isNotBlank(orderBackDO.getReason())){
            backReason = orderBackDO.getReason();
        }
        String shoppingCode = orderOrderDO.getShippingCode()!=null?orderOrderDO.getShippingCode():"无";
        OrderShippingDO orderShippingDO = orderShippingDao.getByOrderId(orderOrderDO.getId());

        WxMaKefuMessage wxMaKefuMessage = new WxMaKefuMessage();
        //发送文字
        wxMaKefuMessage.setMsgType("text");
        wxMaKefuMessage.setToUser(openID);
        TextMessageBuilder textMessageBuilder = WxMaKefuMessage.newTextBuilder().content("" +
                "★反馈人："+memberUserDO.getName()+"\n" +
                "★订单号："+orderOrderDO.getOrderSn()+"\n" +
                "★商品名称："+goodsGoodsDO.getName()+"\n" +
                "★商品数量："+total+"\n" +
                "★原始单号："+shoppingCode+"\n" +
                "★寄回单号："+backExpressCode+"\n" +
                "★下单时间："+ DateUtil.format(orderOrderDO.getCreateAt(), DateUtils.DATE_TIME_PATTERN)+"\n" +
                "★订单信息："+orderShippingDO.getReceiverName()+" "+orderShippingDO.getReceiverPhone()+ " "+orderShippingDO.getReceiverAddress()+ "\n" +
                "★售后原因："+backReason+"\n" +
                "★售后类型："+ OrderStatus.getStatus(orderOrderDO.getStatus()) +"\n" +
                "★我的处理方案：手动填写\n" +
                "★退款金额：手动填写");
        wxMaKefuMessage.setText(textMessageBuilder.build().getText());
       // System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> textMessageBuilder.build().getText():"+textMessageBuilder.build().getText());
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> textMessageBuilder.build().getText().getContent():"+textMessageBuilder.build().getText().getContent());
        wxService.getMsgService().sendKefuMsg(wxMaKefuMessage);

        //发送图片
           /* ImageMessageBuilder imageMessageBuilder = WxMaKefuMessage.newImageBuilder();
            imageMessageBuilder.mediaId(image.getMediaId());
            wxMaKefuMessage.setMsgType("image");
            wxMaKefuMessage.setImage(new WxMaKefuMessage.KfImage(image.getMediaId()));
            wxService.getMsgService().sendKefuMsg(wxMaKefuMessage);*/
    }

    public String parseXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>\n");
        Set es = map.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(null != v && !"".equals(v) && !"appkey".equals(k)) {

                sb.append("<" + k +">" + v + "</" + k + ">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }


}


